[[...path]].page.tsx 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637
  1. import React, { ReactElement, useEffect } from 'react';
  2. import EventEmitter from 'events';
  3. import {
  4. isClient, isIPageInfoForEntity, pagePathUtils, pathUtils,
  5. } from '@growi/core';
  6. import type {
  7. IDataWithMeta, IPageInfoForEntity, IPagePopulatedToShowRevision, IUser, IUserHasId,
  8. } from '@growi/core';
  9. import ExtensibleCustomError from 'extensible-custom-error';
  10. import {
  11. NextPage, GetServerSideProps, GetServerSidePropsContext,
  12. } from 'next';
  13. import { serverSideTranslations } from 'next-i18next/serverSideTranslations';
  14. import dynamic from 'next/dynamic';
  15. import Head from 'next/head';
  16. import { useRouter } from 'next/router';
  17. import superjson from 'superjson';
  18. import { Comments } from '~/components/Comments';
  19. import { PageAlerts } from '~/components/PageAlert/PageAlerts';
  20. // import { useTranslation } from '~/i18n';
  21. import { CurrentPageContentFooter } from '~/components/PageContentFooter';
  22. import { DrawioViewerScript } from '~/components/Script/DrawioViewerScript';
  23. import { UsersHomePageFooterProps } from '~/components/UsersHomePageFooter';
  24. import type { CrowiRequest } from '~/interfaces/crowi-request';
  25. // import { renderScriptTagByName, renderHighlightJsStyleTag } from '~/service/cdn-resources-loader';
  26. // import { useRendererSettings } from '~/stores/renderer';
  27. // import { EditorMode, useEditorMode, useIsMobile } from '~/stores/ui';
  28. import type { EditorConfig } from '~/interfaces/editor-settings';
  29. import type { RendererConfig } from '~/interfaces/services/renderer';
  30. import type { ISidebarConfig } from '~/interfaces/sidebar-config';
  31. import type { IUserUISettings } from '~/interfaces/user-ui-settings';
  32. import type { PageModel, PageDocument } from '~/server/models/page';
  33. import type { PageRedirectModel } from '~/server/models/page-redirect';
  34. import type { UserUISettingsModel } from '~/server/models/user-ui-settings';
  35. import { useEditingMarkdown } from '~/stores/editor';
  36. import { useSWRxCurrentPage, useSWRxIsGrantNormalized } from '~/stores/page';
  37. import { useRedirectFrom } from '~/stores/page-redirect';
  38. import {
  39. useEditorMode, useSelectedGrant,
  40. usePreferDrawerModeByUser, usePreferDrawerModeOnEditByUser, useSidebarCollapsed, useCurrentSidebarContents, useCurrentProductNavWidth,
  41. } from '~/stores/ui';
  42. import { useSetupGlobalSocket, useSetupGlobalSocketForPage } from '~/stores/websocket';
  43. import loggerFactory from '~/utils/logger';
  44. // import { isUserPage, isTrashPage, isSharedPage } from '~/utils/path-utils';
  45. // import GrowiSubNavigation from '../client/js/components/Navbar/GrowiSubNavigation';
  46. // import GrowiSubNavigationSwitcher from '../client/js/components/Navbar/GrowiSubNavigationSwitcher';
  47. import { DescendantsPageListModal } from '../components/DescendantsPageListModal';
  48. import { BasicLayout } from '../components/Layout/BasicLayout';
  49. import GrowiContextualSubNavigation from '../components/Navbar/GrowiContextualSubNavigation';
  50. import DisplaySwitcher from '../components/Page/DisplaySwitcher';
  51. // import { serializeUserSecurely } from '../server/models/serializers/user-serializer';
  52. // import PageStatusAlert from '../client/js/components/PageStatusAlert';
  53. import {
  54. useCurrentUser,
  55. useIsLatestRevision,
  56. useIsForbidden, useIsNotFound, useIsSharedUser,
  57. useIsEnabledStaleNotification, useIsIdenticalPath,
  58. useIsSearchServiceConfigured, useIsSearchServiceReachable, useDisableLinkSharing,
  59. useDrawioUri, useHackmdUri, useDefaultIndentSize, useIsIndentSizeForced,
  60. useIsAclEnabled, useIsSearchPage, useTemplateTagData, useTemplateBodyData, useIsEnabledAttachTitleHeader,
  61. useCsrfToken, useIsSearchScopeChildrenAsDefault, useCurrentPageId, useCurrentPathname,
  62. useIsSlackConfigured, useRendererConfig,
  63. useEditorConfig, useIsAllReplyShown, useIsUploadableFile, useIsUploadableImage, useCustomizedLogoSrc, useIsContainerFluid,
  64. } from '../stores/context';
  65. import {
  66. CommonProps, getNextI18NextConfig, getServerSideCommonProps, generateCustomTitle,
  67. } from './utils/commons';
  68. // import { useCurrentPageSWR } from '../stores/page';
  69. declare global {
  70. // eslint-disable-next-line vars-on-top, no-var
  71. var globalEmitter: EventEmitter;
  72. }
  73. const NotCreatablePage = dynamic(() => import('../components/NotCreatablePage').then(mod => mod.NotCreatablePage), { ssr: false });
  74. const ForbiddenPage = dynamic(() => import('../components/ForbiddenPage'), { ssr: false });
  75. const UnsavedAlertDialog = dynamic(() => import('../components/UnsavedAlertDialog'), { ssr: false });
  76. const GrowiSubNavigationSwitcher = dynamic(() => import('../components/Navbar/GrowiSubNavigationSwitcher'), { ssr: false });
  77. const UsersHomePageFooter = dynamic<UsersHomePageFooterProps>(() => import('../components/UsersHomePageFooter')
  78. .then(mod => mod.UsersHomePageFooter), { ssr: false });
  79. const DrawioModal = dynamic(() => import('../components/PageEditor/DrawioModal').then(mod => mod.DrawioModal), { ssr: false });
  80. const HandsontableModal = dynamic(() => import('../components/PageEditor/HandsontableModal').then(mod => mod.HandsontableModal), { ssr: false });
  81. const PageStatusAlert = dynamic(() => import('../components/PageStatusAlert').then(mod => mod.PageStatusAlert), { ssr: false });
  82. const logger = loggerFactory('growi:pages:all');
  83. const {
  84. isPermalink: _isPermalink, isUsersHomePage, isTrashPage: _isTrashPage, isUserPage, isCreatablePage, isTopPage,
  85. } = pagePathUtils;
  86. const { removeHeadingSlash } = pathUtils;
  87. type IPageToShowRevisionWithMeta = IDataWithMeta<IPagePopulatedToShowRevision & PageDocument, IPageInfoForEntity>;
  88. type IPageToShowRevisionWithMetaSerialized = IDataWithMeta<string, string>;
  89. superjson.registerCustom<IPageToShowRevisionWithMeta, IPageToShowRevisionWithMetaSerialized>(
  90. {
  91. isApplicable: (v): v is IPageToShowRevisionWithMeta => {
  92. return v?.data != null
  93. && v?.data.toObject != null
  94. && v?.meta != null
  95. && isIPageInfoForEntity(v.meta);
  96. },
  97. serialize: (v) => {
  98. return {
  99. data: superjson.stringify(v.data.toObject()),
  100. meta: superjson.stringify(v.meta),
  101. };
  102. },
  103. deserialize: (v) => {
  104. return {
  105. data: superjson.parse(v.data),
  106. meta: v.meta != null ? superjson.parse(v.meta) : undefined,
  107. };
  108. },
  109. },
  110. 'IPageToShowRevisionWithMetaTransformer',
  111. );
  112. const IdenticalPathPage = (): JSX.Element => {
  113. const IdenticalPathPage = dynamic(() => import('../components/IdenticalPathPage').then(mod => mod.IdenticalPathPage), { ssr: false });
  114. return <IdenticalPathPage />;
  115. };
  116. const PutbackPageModal = (): JSX.Element => {
  117. const PutbackPageModal = dynamic(() => import('../components/PutbackPageModal'), { ssr: false });
  118. return <PutbackPageModal />;
  119. };
  120. type Props = CommonProps & {
  121. currentUser: IUser,
  122. pageWithMeta: IPageToShowRevisionWithMeta | null,
  123. // pageUser?: any,
  124. redirectFrom?: string;
  125. // shareLinkId?: string;
  126. isLatestRevision?: boolean,
  127. isIdenticalPathPage?: boolean,
  128. isForbidden: boolean,
  129. isNotFound: boolean,
  130. isNotCreatablePage: boolean,
  131. // isAbleToDeleteCompletely: boolean,
  132. templateTagData?: string[],
  133. templateBodyData?: string,
  134. isSearchServiceConfigured: boolean,
  135. isSearchServiceReachable: boolean,
  136. isSearchScopeChildrenAsDefault: boolean,
  137. isSlackConfigured: boolean,
  138. // isMailerSetup: boolean,
  139. isAclEnabled: boolean,
  140. // hasSlackConfig: boolean,
  141. drawioUri: string | null,
  142. hackmdUri: string,
  143. noCdn: string,
  144. // highlightJsStyle: string,
  145. isAllReplyShown: boolean,
  146. isContainerFluid: boolean,
  147. editorConfig: EditorConfig,
  148. isEnabledStaleNotification: boolean,
  149. isEnabledAttachTitleHeader: boolean,
  150. // isEnabledLinebreaks: boolean,
  151. // isEnabledLinebreaksInComments: boolean,
  152. adminPreferredIndentSize: number,
  153. isIndentSizeForced: boolean,
  154. disableLinkSharing: boolean,
  155. rendererConfig: RendererConfig,
  156. // UI
  157. userUISettings?: IUserUISettings
  158. // Sidebar
  159. sidebarConfig: ISidebarConfig,
  160. };
  161. const Page: NextPage<Props> = (props: Props) => {
  162. // const { t } = useTranslation();
  163. const router = useRouter();
  164. const { data: currentUser } = useCurrentUser(props.currentUser ?? null);
  165. // register global EventEmitter
  166. if (isClient() && window.globalEmitter == null) {
  167. window.globalEmitter = new EventEmitter();
  168. }
  169. // commons
  170. useEditorConfig(props.editorConfig);
  171. useCsrfToken(props.csrfToken);
  172. useCustomizedLogoSrc(props.customizedLogoSrc);
  173. // UserUISettings
  174. usePreferDrawerModeByUser(props.userUISettings?.preferDrawerModeByUser ?? props.sidebarConfig.isSidebarDrawerMode);
  175. usePreferDrawerModeOnEditByUser(props.userUISettings?.preferDrawerModeOnEditByUser);
  176. useSidebarCollapsed(props.userUISettings?.isSidebarCollapsed ?? props.sidebarConfig.isSidebarClosedAtDockMode);
  177. useCurrentSidebarContents(props.userUISettings?.currentSidebarContents);
  178. useCurrentProductNavWidth(props.userUISettings?.currentProductNavWidth);
  179. // page
  180. useIsLatestRevision(props.isLatestRevision);
  181. useIsContainerFluid(props.isContainerFluid);
  182. // useOwnerOfCurrentPage(props.pageUser != null ? JSON.parse(props.pageUser) : null);
  183. useIsForbidden(props.isForbidden);
  184. useIsNotFound(props.isNotFound);
  185. // useIsNotCreatable(props.IsNotCreatable);
  186. useRedirectFrom(props.redirectFrom);
  187. // useShared();
  188. // useShareLinkId(props.shareLinkId);
  189. useIsSharedUser(false); // this page cann't be routed for '/share'
  190. useIsIdenticalPath(false); // TODO: need to initialize from props
  191. // useIsAbleToDeleteCompletely(props.isAbleToDeleteCompletely);
  192. useIsEnabledStaleNotification(props.isEnabledStaleNotification);
  193. useIsSearchPage(false);
  194. useTemplateTagData(props.templateTagData);
  195. useTemplateBodyData(props.templateBodyData);
  196. useIsEnabledAttachTitleHeader(props.isEnabledAttachTitleHeader);
  197. useIsSearchServiceConfigured(props.isSearchServiceConfigured);
  198. useIsSearchServiceReachable(props.isSearchServiceReachable);
  199. useIsSearchScopeChildrenAsDefault(props.isSearchScopeChildrenAsDefault);
  200. useIsSlackConfigured(props.isSlackConfigured);
  201. // useIsMailerSetup(props.isMailerSetup);
  202. useIsAclEnabled(props.isAclEnabled);
  203. // useHasSlackConfig(props.hasSlackConfig);
  204. useDrawioUri(props.drawioUri);
  205. useHackmdUri(props.hackmdUri);
  206. // useNoCdn(props.noCdn);
  207. useDefaultIndentSize(props.adminPreferredIndentSize);
  208. useIsIndentSizeForced(props.isIndentSizeForced);
  209. useDisableLinkSharing(props.disableLinkSharing);
  210. useRendererConfig(props.rendererConfig);
  211. // useRendererSettings(props.rendererSettingsStr != null ? JSON.parse(props.rendererSettingsStr) : undefined);
  212. // useGrowiRendererConfig(props.growiRendererConfigStr != null ? JSON.parse(props.growiRendererConfigStr) : undefined);
  213. useIsAllReplyShown(props.isAllReplyShown);
  214. useIsUploadableFile(props.editorConfig.upload.isUploadableFile);
  215. useIsUploadableImage(props.editorConfig.upload.isUploadableImage);
  216. const { pageWithMeta, userUISettings } = props;
  217. const pageId = pageWithMeta?.data._id;
  218. const pagePath = pageWithMeta?.data.path ?? (!_isPermalink(props.currentPathname) ? props.currentPathname : undefined);
  219. useCurrentPageId(pageId ?? null);
  220. // useIsNotCreatable(props.isForbidden || !isCreatablePage(pagePath)); // TODO: need to include props.isIdentical
  221. useCurrentPathname(props.currentPathname);
  222. const { data: currentPage } = useSWRxCurrentPage(undefined, pageWithMeta?.data ?? null); // store initial data
  223. useEditingMarkdown(pageWithMeta?.data.revision?.body);
  224. const { data: grantData } = useSWRxIsGrantNormalized(pageId);
  225. const { mutate: mutateSelectedGrant } = useSelectedGrant();
  226. const { getClassNamesByEditorMode } = useEditorMode();
  227. useSetupGlobalSocket();
  228. useSetupGlobalSocketForPage(pageId);
  229. const shouldRenderPutbackPageModal = pageWithMeta != null
  230. ? _isTrashPage(pageWithMeta.data.path)
  231. : false;
  232. // sync grant data
  233. useEffect(() => {
  234. mutateSelectedGrant(grantData?.grantData.currentPageGrant);
  235. }, [grantData?.grantData.currentPageGrant, mutateSelectedGrant]);
  236. // sync pathname by Shallow Routing https://nextjs.org/docs/routing/shallow-routing
  237. useEffect(() => {
  238. const decodedURI = decodeURI(window.location.pathname);
  239. if (isClient() && decodedURI !== props.currentPathname) {
  240. router.replace(props.currentPathname, undefined, { shallow: true });
  241. }
  242. }, [props.currentPathname, router]);
  243. const classNames: string[] = [];
  244. const isSidebar = pagePath === '/Sidebar';
  245. classNames.push(...getClassNamesByEditorMode(isSidebar));
  246. const isTopPagePath = isTopPage(pageWithMeta?.data.path ?? '');
  247. const isContainerFluidEachPage = currentPage == null || !('expandContentWidth' in currentPage)
  248. ? null
  249. : currentPage.expandContentWidth;
  250. const isContainerFluidDefault = props.isContainerFluid;
  251. const isContainerFluid = isContainerFluidEachPage ?? isContainerFluidDefault;
  252. const title = generateCustomTitle(props, 'GROWI');
  253. return (
  254. <>
  255. <Head>
  256. <title>{title}</title>
  257. </Head>
  258. <DrawioViewerScript />
  259. <BasicLayout className={classNames.join(' ')} expandContainer={isContainerFluid}>
  260. <div className="h-100 d-flex flex-column justify-content-between">
  261. <header className="py-0 position-relative">
  262. <div id="grw-subnav-container">
  263. <GrowiContextualSubNavigation isLinkSharingDisabled={props.disableLinkSharing} />
  264. </div>
  265. </header>
  266. <div className="d-edit-none">
  267. <GrowiSubNavigationSwitcher />
  268. </div>
  269. <div id="grw-subnav-sticky-trigger" className="sticky-top"></div>
  270. <div id="grw-fav-sticky-trigger" className="sticky-top"></div>
  271. <div className="flex-grow-1">
  272. <div id="main" className={`main ${isUsersHomePage(props.currentPathname) && 'user-page'}`}>
  273. <div id="content-main" className="content-main grw-container-convertible">
  274. { props.isIdenticalPathPage && <IdenticalPathPage /> }
  275. { !props.isIdenticalPathPage && (
  276. <>
  277. <PageAlerts />
  278. { props.isForbidden && <ForbiddenPage /> }
  279. { props.isNotCreatablePage && <NotCreatablePage />}
  280. { !props.isForbidden && !props.isNotCreatablePage && <DisplaySwitcher />}
  281. {/* <DisplaySwitcher /> */}
  282. <PageStatusAlert />
  283. </>
  284. ) }
  285. {/* <div className="col-xl-2 col-lg-3 d-none d-lg-block revision-toc-container">
  286. <div id="revision-toc" className="revision-toc mt-3 sps sps--abv" data-sps-offset="123">
  287. <div id="revision-toc-content" className="revision-toc-content"></div>
  288. </div>
  289. </div> */}
  290. </div>
  291. </div>
  292. </div>
  293. { !props.isIdenticalPathPage && !props.isNotFound && (
  294. <footer className="footer d-edit-none">
  295. { pageWithMeta != null && pagePath != null && !isTopPagePath && (
  296. <Comments pageId={pageId} pagePath={pagePath} revision={pageWithMeta.data.revision} />
  297. ) }
  298. { pageWithMeta != null && isUsersHomePage(pageWithMeta.data.path) && (
  299. <UsersHomePageFooter creatorId={pageWithMeta.data.creator._id}/>
  300. ) }
  301. <CurrentPageContentFooter />
  302. </footer>
  303. )}
  304. <UnsavedAlertDialog />
  305. <DescendantsPageListModal />
  306. <DrawioModal />
  307. <HandsontableModal />
  308. {shouldRenderPutbackPageModal && <PutbackPageModal />}
  309. </div>
  310. </BasicLayout>
  311. </>
  312. );
  313. };
  314. function getPageIdFromPathname(currentPathname: string): string | null {
  315. return _isPermalink(currentPathname) ? removeHeadingSlash(currentPathname) : null;
  316. }
  317. class MultiplePagesHitsError extends ExtensibleCustomError {
  318. pagePath: string;
  319. constructor(pagePath: string) {
  320. super(`MultiplePagesHitsError occured by '${pagePath}'`);
  321. this.pagePath = pagePath;
  322. }
  323. }
  324. async function injectPageData(context: GetServerSidePropsContext, props: Props): Promise<void> {
  325. const { model: mongooseModel } = await import('mongoose');
  326. const req: CrowiRequest = context.req as CrowiRequest;
  327. const { crowi } = req;
  328. const { revisionId } = req.query;
  329. const Page = crowi.model('Page') as PageModel;
  330. const PageRedirect = mongooseModel('PageRedirect') as PageRedirectModel;
  331. const { pageService } = crowi;
  332. let currentPathname = props.currentPathname;
  333. const pageId = getPageIdFromPathname(currentPathname);
  334. const isPermalink = _isPermalink(currentPathname);
  335. const { user } = req;
  336. if (!isPermalink) {
  337. // check redirects
  338. const chains = await PageRedirect.retrievePageRedirectEndpoints(currentPathname);
  339. if (chains != null) {
  340. // overwrite currentPathname
  341. currentPathname = chains.end.toPath;
  342. props.currentPathname = currentPathname;
  343. // set redirectFrom
  344. props.redirectFrom = chains.start.fromPath;
  345. }
  346. // check whether the specified page path hits to multiple pages
  347. const count = await Page.countByPathAndViewer(currentPathname, user, null, true);
  348. if (count > 1) {
  349. throw new MultiplePagesHitsError(currentPathname);
  350. }
  351. }
  352. const pageWithMeta: IPageToShowRevisionWithMeta | null = await pageService.findPageAndMetaDataByViewer(pageId, currentPathname, user, true); // includeEmpty = true, isSharedPage = false
  353. const page = pageWithMeta?.data as unknown as PageDocument;
  354. // add user to seen users
  355. if (page != null && user != null) {
  356. await page.seen(user);
  357. }
  358. // populate & check if the revision is latest
  359. if (page != null) {
  360. page.initLatestRevisionField(revisionId);
  361. await page.populateDataToShowRevision();
  362. props.isLatestRevision = page.isLatestRevision();
  363. }
  364. if (page == null && user != null) {
  365. const templateData = await Page.findTemplate(props.currentPathname);
  366. if (templateData != null) {
  367. props.templateTagData = templateData.templateTags as string[];
  368. props.templateBodyData = templateData.templateBody as string;
  369. }
  370. }
  371. props.pageWithMeta = pageWithMeta;
  372. }
  373. async function injectUserUISettings(context: GetServerSidePropsContext, props: Props): Promise<void> {
  374. const { model: mongooseModel } = await import('mongoose');
  375. const req = context.req as CrowiRequest<IUserHasId & any>;
  376. const { user } = req;
  377. const UserUISettings = mongooseModel('UserUISettings') as UserUISettingsModel;
  378. const userUISettings = user == null ? null : await UserUISettings.findOne({ user: user._id }).exec();
  379. if (userUISettings != null) {
  380. props.userUISettings = userUISettings.toObject();
  381. }
  382. }
  383. async function injectRoutingInformation(context: GetServerSidePropsContext, props: Props): Promise<void> {
  384. const req: CrowiRequest = context.req as CrowiRequest;
  385. const { crowi } = req;
  386. const Page = crowi.model('Page') as PageModel;
  387. const { currentPathname } = props;
  388. const pageId = getPageIdFromPathname(currentPathname);
  389. const isPermalink = _isPermalink(currentPathname);
  390. const page = props.pageWithMeta?.data;
  391. if (props.isIdenticalPathPage) {
  392. // TBD
  393. }
  394. else if (page == null) {
  395. props.isNotFound = true;
  396. props.isNotCreatablePage = !isCreatablePage(currentPathname);
  397. // check the page is forbidden or just does not exist.
  398. const count = isPermalink ? await Page.count({ _id: pageId }) : await Page.count({ path: currentPathname });
  399. props.isForbidden = count > 0;
  400. }
  401. else {
  402. props.isNotFound = page.isEmpty;
  403. // /62a88db47fed8b2d94f30000 ==> /path/to/page
  404. if (isPermalink && page.isEmpty) {
  405. props.currentPathname = page.path;
  406. }
  407. // /path/to/page ==> /62a88db47fed8b2d94f30000
  408. if (!isPermalink && !page.isEmpty) {
  409. const isToppage = pagePathUtils.isTopPage(props.currentPathname);
  410. if (!isToppage) {
  411. props.currentPathname = `/${page._id}`;
  412. }
  413. }
  414. }
  415. }
  416. // async function injectPageUserInformation(context: GetServerSidePropsContext, props: Props): Promise<void> {
  417. // const req: CrowiRequest = context.req as CrowiRequest;
  418. // const { crowi } = req;
  419. // const UserModel = crowi.model('User');
  420. // if (isUserPage(props.currentPagePath)) {
  421. // const user = await UserModel.findUserByUsername(UserModel.getUsernameByPath(props.currentPagePath));
  422. // if (user != null) {
  423. // props.pageUser = JSON.stringify(user.toObject());
  424. // }
  425. // }
  426. // }
  427. function injectServerConfigurations(context: GetServerSidePropsContext, props: Props): void {
  428. const req: CrowiRequest = context.req as CrowiRequest;
  429. const { crowi } = req;
  430. const {
  431. appService, searchService, configManager, aclService, slackNotificationService, mailService,
  432. } = crowi;
  433. props.isSearchServiceConfigured = searchService.isConfigured;
  434. props.isSearchServiceReachable = searchService.isReachable;
  435. props.isSearchScopeChildrenAsDefault = configManager.getConfig('crowi', 'customize:isSearchScopeChildrenAsDefault');
  436. props.isSlackConfigured = crowi.slackIntegrationService.isSlackConfigured;
  437. // props.isMailerSetup = mailService.isMailerSetup;
  438. props.isAclEnabled = aclService.isAclEnabled();
  439. // props.hasSlackConfig = slackNotificationService.hasSlackConfig();
  440. props.drawioUri = configManager.getConfig('crowi', 'app:drawioUri');
  441. props.hackmdUri = configManager.getConfig('crowi', 'app:hackmdUri');
  442. props.noCdn = configManager.getConfig('crowi', 'app:noCdn');
  443. // props.highlightJsStyle = configManager.getConfig('crowi', 'customize:highlightJsStyle');
  444. props.isAllReplyShown = configManager.getConfig('crowi', 'customize:isAllReplyShown');
  445. props.isContainerFluid = configManager.getConfig('crowi', 'customize:isContainerFluid');
  446. props.isEnabledStaleNotification = configManager.getConfig('crowi', 'customize:isEnabledStaleNotification');
  447. // props.isEnabledLinebreaks = configManager.getConfig('markdown', 'markdown:isEnabledLinebreaks');
  448. // props.isEnabledLinebreaksInComments = configManager.getConfig('markdown', 'markdown:isEnabledLinebreaksInComments');
  449. props.disableLinkSharing = configManager.getConfig('crowi', 'security:disableLinkSharing');
  450. props.editorConfig = {
  451. upload: {
  452. isUploadableFile: crowi.fileUploadService.getFileUploadEnabled(),
  453. isUploadableImage: crowi.fileUploadService.getIsUploadable(),
  454. },
  455. };
  456. props.adminPreferredIndentSize = configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize');
  457. props.isIndentSizeForced = configManager.getConfig('markdown', 'markdown:isIndentSizeForced');
  458. props.isEnabledAttachTitleHeader = configManager.getConfig('crowi', 'customize:isEnabledAttachTitleHeader');
  459. props.rendererConfig = {
  460. isEnabledLinebreaks: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaks'),
  461. isEnabledLinebreaksInComments: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaksInComments'),
  462. adminPreferredIndentSize: configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize'),
  463. isIndentSizeForced: configManager.getConfig('markdown', 'markdown:isIndentSizeForced'),
  464. plantumlUri: process.env.PLANTUML_URI ?? null,
  465. blockdiagUri: process.env.BLOCKDIAG_URI ?? null,
  466. // XSS Options
  467. isEnabledXssPrevention: configManager.getConfig('markdown', 'markdown:xss:isEnabledPrevention'),
  468. attrWhiteList: crowi.xssService.getAttrWhiteList(),
  469. tagWhiteList: crowi.xssService.getTagWhiteList(),
  470. highlightJsStyleBorder: crowi.configManager.getConfig('crowi', 'customize:highlightJsStyleBorder'),
  471. };
  472. props.sidebarConfig = {
  473. isSidebarDrawerMode: configManager.getConfig('crowi', 'customize:isSidebarDrawerMode'),
  474. isSidebarClosedAtDockMode: configManager.getConfig('crowi', 'customize:isSidebarClosedAtDockMode'),
  475. };
  476. }
  477. /**
  478. * for Server Side Translations
  479. * @param context
  480. * @param props
  481. * @param namespacesRequired
  482. */
  483. async function injectNextI18NextConfigurations(context: GetServerSidePropsContext, props: Props, namespacesRequired?: string[] | undefined): Promise<void> {
  484. const nextI18NextConfig = await getNextI18NextConfig(serverSideTranslations, context, namespacesRequired);
  485. props._nextI18Next = nextI18NextConfig._nextI18Next;
  486. }
  487. export const getServerSideProps: GetServerSideProps = async(context: GetServerSidePropsContext) => {
  488. const req = context.req as CrowiRequest<IUserHasId & any>;
  489. const { user } = req;
  490. const result = await getServerSideCommonProps(context);
  491. // check for presence
  492. // see: https://github.com/vercel/next.js/issues/19271#issuecomment-730006862
  493. if (!('props' in result)) {
  494. throw new Error('invalid getSSP result');
  495. }
  496. const props: Props = result.props as Props;
  497. if (props.redirectDestination != null) {
  498. return {
  499. redirect: {
  500. permanent: false,
  501. destination: props.redirectDestination,
  502. },
  503. };
  504. }
  505. if (user != null) {
  506. props.currentUser = user.toObject();
  507. }
  508. try {
  509. await injectPageData(context, props);
  510. }
  511. catch (err) {
  512. if (err instanceof MultiplePagesHitsError) {
  513. props.isIdenticalPathPage = true;
  514. }
  515. else {
  516. throw err;
  517. }
  518. }
  519. await injectUserUISettings(context, props);
  520. await injectRoutingInformation(context, props);
  521. injectServerConfigurations(context, props);
  522. await injectNextI18NextConfigurations(context, props, ['translation']);
  523. return {
  524. props,
  525. };
  526. };
  527. export default Page;